/**
 * 提供企业微信列表及相关操作函数
 */
import { keywordCompare } from '@gnlab/utils'
import partition from 'lodash/partition'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import { Status } from '@/services/qywxs'
import type { QywxInfo } from '@/services/qywxs'

const { Normal, Preparing } = Status
const statusCanShow = new Set([Normal, Preparing]) // 哪几种状态的企业微信要显示出来

export default function useQywxList(params: { search?: string } = {}) {
  const { search: rawSearch = '' } = params
  const search = rawSearch.trim()

  const [allQywxs, focused] = useStreams(services.qywxs.qywxs, services.qywxs.focus.focused)
  const qywxs = useMemo(
    () => [...allQywxs.values()].filter(qywx => statusCanShow.has(qywx.status)),
    [allQywxs],
  )
  const filteredQywxs = useMemo(
    () =>
      qywxs.filter(
        qywx => !search || keywordCompare(search, qywx.friendlyFullName) || qywx.wxid === search,
      ),
    [qywxs, search],
  )
  const [normalQywxs, preparingQywxs] = useMemo(
    () => partition(filteredQywxs, v => v.status !== Status.Preparing),
    [filteredQywxs],
  )

  const logout = useCallback((wxids: string[]) => services.qywxs.logout(wxids), [])
  const transfer = useCallback(
    async (qywxs: QywxInfo[], toUserId: string, toUserName: string) =>
      services.qywxs.transfers.transfer(qywxs, { id: toUserId, name: toUserName }),
    [],
  )
  const focus = useCallback((wxid: string) => services.qywxs.focus.focus(wxid), [])
  const cancelFocus = useCallback(() => services.qywxs.focus.cancel(), [])

  return {
    qywxs,
    filteredQywxs,
    normalQywxs,
    preparingQywxs,
    focused,
    logout,
    transfer,
    focus,
    cancelFocus,
  }
}
